
$(function () {
    var loresetId = $("#loresetId").val();
    var setting={
        async: {
            dataType: 'json',
            dataFilter: function (treeId, treeNode, response) {
                if (response.success) {
                    return response.entity;
                } else {
                    icModale(0, response.message);
                }
            },
            enable: true,
            type: 'post',
            otherParam:{'loresetId':loresetId},
            url: baseloaction+'/admin/manage/point/ajaxLoresetPointList'
        },
        view: {
            addHoverDom:function (treeId,treeNode) {//自定义添加按钮
                var sObj = $("#" + treeNode.tId + "_span");
                if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0 || treeNode.parentId>0) return;
                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加知识点' onfocus='this.blur();'></span>";
                sObj.after(addStr);
                var btn = $("#addBtn_"+treeNode.tId);
                if (btn) btn.bind("click", function(){
                    initUpdateOrAdd(treeNode.id,0);
                    return false;
                });
            },
            removeHoverDom:function(treeId, treeNode) {//鼠标离开删除自定义按钮
                $("#addBtn_"+treeNode.tId).unbind().remove();
            },
            showLine:true,
            selectedMulti: false,
            nameIsHTML:true,
            fontCss:function (treeId,treeNode) {
                if(typeof treeNode.highlight=='undefined' || treeNode.highlight==false){
                    return {color:"#333", "font-weight":"normal"};
                }else{
                    return {color:"#A60000", "font-weight":"bold"};
                }
            }
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true,
                idKey:'id',
                pIdKey:'parentId',
                rootPId:null
            },
            key:{
                name :'pointName',
                title :'pointName'
            }
        },
        edit: {
            enable: true,
            removeTitle:function (treeId,treeNode) {
                return "删除："+treeNode.pointName;
            },
            renameTitle:function (treeId,treeNode) {
                return "修改："+treeNode.pointName;
            }
        },
        callback:{
            //用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
            beforeDrop:updateLoresetPointParnet,
            //初始化修改
            beforeEditName:initUpdateLoresetPoint,
            //用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
            beforeRemove:initDeleteLoresetPoint,
            //异步加载数据错误
            onAsyncError: function () {
                icModale(0, "系统错误，知识点数据加载失败");
            },
            onAsyncSuccess: function (event, treeId) {
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var arr = treeObj.getNodes();
                if(arr && arr.length>0){
                    //展开所有的节点
                    treeObj.expandAll(true);
                }else{
                    setNotDataMsg();
                }
            }
        }
    };
    //如果没有知识数据这显示
    function setNotDataMsg() {
        $("#loreset-point-jstree").html('<p id="not-data-msg"><span class="c-4e fs16">亲，还没有创建知识点数据~~~</span></p>');
    }
    //获取知识点数量
    function getCount() {
        return $('#loreset-point-jstree li').size();
    }
    //初始化树结构
    $.fn.zTree.init($("#loreset-point-jstree"), setting);

    //全选
    allSelete('all-loresetPoint',function (status) {
        var treeObj = $.fn.zTree.getZTreeObj("loreset-point-jstree");
        treeObj.checkAllNodes(status);
    });
    $("body").on("keyup","#search-loreset-point",function () {//知识点高亮搜索
        var keyword = this.value;
        var treeObj = $.fn.zTree.getZTreeObj("loreset-point-jstree");
        var list = treeObj.getNodesByFilter(function (node) {
            return true;
        });
        if(!$.isEmptyObject(list) && list.length>0){
            $.each(list,function (index,node){
                node.highlight  = false;
                treeObj.updateNode(node);
            });
        }
        var nodes = treeObj.getNodesByFilter(function (node) {
            if(!$.isEmptyObject(keyword) && $.trim(keyword)!='' && node.pointName.indexOf(keyword)!=-1){
                return true;
            }else{
                return false;
            }
        });
        if(!$.isEmptyObject(nodes) && nodes.length>0){
            $.each(nodes,function (index,node) {
                node.highlight=true;
                treeObj.updateNode(node);
            });
        }
    }).on("click","#saveLoresetPoint",function () {//保存知识点
        var zTree = $.fn.zTree.getZTreeObj('loreset-point-jstree');
        var _loresetPointId = $("#id").val();
        if(!$.isEmptyObject(_loresetPointId)){
            $.ajax({
                url: baseloaction + "/admin/manage/loresetPoint/updateLoresetPoint",
                data: $("#loresetPointForm").serialize(),
                type:"post",
                dataType:"json",
                success: function (result) {
                    if(result.success){
                        icModale(0, result.message);
                        var node = zTree.getNodesByParam('id', result.entity.id);
                        var entity = result.entity;
                        if (node.length > 0) {
                            for (var key in entity) {
                                node[0][key] = entity[key];
                            }
                            zTree.updateNode(node[0]);
                            clearForm();
                        }
                    }else {
                        icModale(0,result.message);
                    }
                },
                error: function (error) {
                    icModale(0,"系统繁忙,请稍后重试");
                }
            });
        }else {
            $.ajax({
                url: baseloaction + "/admin/manage/loresetPoint/updateLoresetPoint",
                data: $("#loresetPointForm").serialize(),
                type:"post",
                dataType:"json",
                success: function (result) {
                    if(result.success){
                        icModale(0, result.message);
                        var entity = result.entity;
                        zTree.addNodes(null,-1,entity);
                        clearForm();
                    }else {
                        icModale(0,result.message);
                    }
                },
                error: function (error) {
                    icModale(0,"系统繁忙,请稍后重试");
                }
            });
        }
    }).on("click","#delete-batch",function () {//批量删除
        var loresetPointIds = getCheckedNodesIds();
        if($.isEmptyObject(loresetPointIds) || loresetPointIds.length == 0){
            icModale(0,"请勾选要删除的知识点");
        }else {
            icModale(2,"确认要删除所选知识点及子级知识点吗？",3,function () {
                deleteLoresetPoint(loresetPointIds);
            });
        }
    }).on('click', '#create-loreset-point', function() {//添加节点
        initUpdateOrAdd(0,0);
    }).on('click','#back_step',function(){
       window.location.href=baseloaction+"/admin/manage/loreset/initUpdate?id="+$('#loresetId').val();
    });

    //初始化修改
    function initUpdateLoresetPoint(treeId,treeNode) {
        initUpdateOrAdd(0,treeNode.id);
        return false;
    }
    /**
     * 初始化修改/添加知识点页面
     * @param parentId 父级ID
     * @param id 知识点ID（修改时传）
     */
    function initUpdateOrAdd(parentId,id){
        var title = "修改知识点";
        var url = baseloaction + "/admin/manage/point/initUpdate?id="+id;
        var status= false;
        if(id==0){
            title = "新建知识点"
            url = baseloaction + "/admin/manage/point/initAdd?parentId="+parentId+"&loresetId="+loresetId;
            status = true;
        }
        var context = "";
        $.ajax({
            url:url,
            type:'post',
            dataType:'text',
            async:false,
            success:function(result){
                context = result;
            },
            error:function(error){
                icModale(0, "系统错误，操作失败");
            }
        });

        parent.layer.open({
            type: 1,
            title: '<strong>'+title+'</strong><small class="ml10"></small>',
            shadeClose: false,
            shade: [0.3, '#000000'],
            maxmin: true, //开启最大化最小化按钮
            btn:["确认保存","取消"],
            area: winArea,
            content: context,
            yes: function(index, layero){
                var params = $(layero).find("form").serializeJSON();
                params = JSON.stringify(params);
                $.ajax({
                    url: baseloaction +'/admin/manage/point/saveLoresetPoint',
                    contentType:'application/json;charset=utf-8',
                    type:'post',
                    dataType:'json',
                    data:params,
                    success:function (result) {
                        if(result.success==true){
                            var loresetPoint = result.entity;
                            var treeObj = $.fn.zTree.getZTreeObj("loreset-point-jstree");
                            if(status==false){//修改节点
                                var nodeList = treeObj.getNodesByParam("id",loresetPoint.id,null);
                                nodeList[0].pointName = loresetPoint.pointName;
                                nodeList[0].teachingNamePage = loresetPoint.teachingNamePage;
                                nodeList[0].depict = loresetPoint.depict;
                                nodeList[0].frequency = loresetPoint.frequency;
                                nodeList[0].fraction = loresetPoint.fraction;
                                nodeList[0].questionCount = loresetPoint.questionCount;
                                treeObj.updateNode(nodeList[0]);
                            }else{//添加节点
                                var parentId = loresetPoint.parentId;
                                var parentNode = null;
                                if(parentId!=null){
                                    var nodeList = treeObj.getNodesByParam("id",parentId,null);
                                    if(nodeList!=null && nodeList.length > 0){
                                        parentNode = nodeList[0];
                                    }
                                }
                                var nodes = new Array();
                                nodes.push(loresetPoint);
                                treeObj.addNodes(parentNode,nodes);
                                $("#not-data-msg").remove();
                            }
                            parent.layer.close(index);
                        }else{
                            icModale(0, result.message);
                        }
                    },
                    error:function (error) {
                        icModale(0, "系统错误，保存知识点失败");
                    }
                });
            }
        });
    }

    /**
     * 获取勾选状态的节点ID串（半选中不获取）
     * @returns {string}
     */
    function getCheckedNodesIds() {
        var treeObj = $.fn.zTree.getZTreeObj("loreset-point-jstree");
        var nodes = treeObj.getCheckedNodes(true);
        if(!$.isEmptyObject(nodes) && nodes.length>0){
            var loresetPointIds = '';
            $.each(nodes,function (index,em) {
                if(em.check_Child_State ==-1 || em.check_Child_State == 2 ){
                    loresetPointIds += em.id + ',';
                }
            });
            loresetPointIds = loresetPointIds.substring(0,loresetPointIds.length - 1);
            return loresetPointIds;
        }
        return null;
    }

    /**
     * 节点拖拽时，修改节点的父级ID
     * @param treeId 树结构的ID
     * @param treeNodes 被拖拽的节点
     * @param targetNode 目标节点
     * @param moveType 拖拽类型
     * @returns {boolean} true拖拽成功，false拖拽失败
     */
    function updateLoresetPointParnet(treeId, treeNodes, targetNode, moveType) {
        var node = treeNodes[0];
        if(node.isParent){
            icModale(0,"包含子级知识点的知识点不能移动");
            return false;
        }
        if(targetNode.level > 0){
            icModale(0,"知识点最多有二级关联");
            return false;
        }
        var parentId = 0;
        if(moveType=='prev'){//移动到目标节点上面，如果目标节点没有父级则把移动的的父ID设置成0，如果目标节点有父ID则把该父ID设置成远去节点的父ID
            var parent = targetNode.getParentNode();
            if(!$.isEmptyObject(parent)){
                parentId = parent.id;
            }
        }else if(moveType=='inner' || moveType=='next'){//移动到目标节点下面，则把目标节点的ID设置被移动节点的父ID
            parentId = targetNode.id;
        }
        var s = true;
        $.ajax({
            url: baseloaction + '/admin/manage/point/updateLoresetPointParentId',
            type:'post',
            dataType:'json',
            async:false,
            data:{'id':node.id,'parentId':parentId},
            success:function (result) {
                s = result.success;
                if(s==false){
                    icModale(0,result.message);
                }
            },
            error:function (error) {
                s = false;
                icModale(0,"系统错误，知识点移动失败");
            }
        });
        //去保存
        return s;
    }
    //初始化删除
    function initDeleteLoresetPoint(treeId,treeNode) {
        icModale(2,"确认要删除知识点【"+treeNode.pointName+"】及子知识点吗？",3,function () {
            return deleteLoresetPoint(treeNode.id);
        });
        return false;
    }

    //删除知识点
    function deleteLoresetPoint(loresetPointIds) {
        var s = true;
        $.ajax({
            url: baseloaction+'/admin/manage/point/deleteLoresetPoint',
            type:'post',
            data:{'ids':loresetPointIds},
            async:false,
            success:function (result) {
                s = result.success;
                if(result.success==false){
                    icModale(0,result.message);
                }else{
                    var arr = (loresetPointIds+"").split(",");
                    var treeObj = $.fn.zTree.getZTreeObj("loreset-point-jstree");
                    $.each(arr,function (index,em) {
                        if(!$.isEmptyObject(em)){
                            var node = treeObj.getNodeByParam("id",em,null);
                            treeObj.removeNode(node);
                        }
                    });
                }
            },
            error:function (error) {
                s = false;
                icModale(0,"系统繁忙,请稍后重试");
            }
        });
        return s;
    }
});

